import {
  onMounted,
  onBeforeUnmount,
  onActivated,
  onDeactivated,
  unref,
  Ref
} from 'vue'

// 事件注册
export const useRegistered = (add: () => any, remove: () => any) => {
  onMounted(add)
  onActivated(add)

  // remove
  onBeforeUnmount(remove)
  onDeactivated(remove)
}

const useEvents = (type: string, event: EventListener, target: EventTarget | Ref<EventTarget | undefined> = window) => {
  const add = (): void => {
    const element = unref(target)
    if (element) {
      element.addEventListener(type, event, false)
    }
  }

  const remove = (): void => {
    const element = unref(target)
    if (element) {
      element.removeEventListener(type, event, false)
    }
  }

  useRegistered(add, remove)

  return {
    remove
  }
}

export default useEvents
